/**
 * @file 支付明细列表
 * @author wangxiaokun
 * @date 2021/08/11 10:20:40
 */
var dependsList = [
    'layer', 'form', 'table', 'laydate',
    'zmnTable', 'zmnUtils', 'NP', 'oms_work_config'
];
layui.extend({
    oms_work_config: "work/config/zmn.oms.work.config"
}).define(dependsList, function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laydate = layui.laydate;
    var zmnTable = layui.zmnTable;
    var NP = layui.NP;
    var config = layui.oms_work_config;

    var defaultToolbar = ['print'];

    // 时间选择器字段容器
    var datePickerSelectorArray = [
        'dateTime' // 时间
    ];

    var cols = [
        [
            {field:'companyName',title:'子公司', align: "center", templet: function (d) {
                    return d.companyName == 0 ? "工单未完成收款" : d.companyName;
                }},
            {field:'realityTotalAmount',title:'实收总计', align: "center", templet: formatMoneyToYuan('realityTotalAmount')},
            {field:'totalAmount',title:'收款总计', align: "center", templet: formatMoneyToYuan('totalAmount')},
            {field:'channelpayAmount',title:'渠道预收', align: "center", templet: formatMoneyToYuan('channelpayAmount')},
            {field:'alipayAmount',title:'支付宝', align: "center", templet: formatMoneyToYuan('alipayAmount')},
            {field:'weixinpayAmount',title:'微信', align: "center", templet: formatMoneyToYuan('weixinpayAmount')},
            {field:'eciticAmount',title:'银联-中信', align: "center", templet: formatMoneyToYuan('eciticAmount')},
            {field:'bankpayAmount',title:'银行转账', align: "center", templet: formatMoneyToYuan('bankpayAmount')},
            {field:'icbcpayAmount',title:'工行', align: "center", templet: formatMoneyToYuan('icbcpayAmount')},
            {field:'chinaumsAlipayAppAmount',title:'银商-支付宝', align: "center", templet: formatMoneyToYuan('chinaumsAlipayAppAmount')},
            {field:'chinaumsQRAmount',title:'银商-H5', align: "center", templet: formatMoneyToYuan('chinaumsQRAmount')},
            {field:'chinaumsWechatpayAppAmount',title:'银商-微信', align: "center", templet: formatMoneyToYuan('chinaumsWechatpayAppAmount')},
            {field:'baidupayAmount',title:'百度支付', align: "center", templet: formatMoneyToYuan('baidupayAmount')},
            {field:'kuaishoupayAmount',title:'快手支付', align: "center", templet: formatMoneyToYuan('kuaishoupayAmount')},
            {field:'yipayAmount',title:'翼支付', align: "center", templet: formatMoneyToYuan('yipayAmount')},
            {field:'cashAmount',title:'退款总计', align: "center", templet: formatMoneyToYuan('cashAmount')},
            {field:'balancepayAmount',title:'虚拟账户', align: "center", templet: formatMoneyToYuan('balancepayAmount')},
            {field:'duplicateAmount',title:'重复支付', align: "center", templet: formatMoneyToYuan('duplicateAmount')},
            {field:'warrantyAmount',title:'质保金支付', align: "center", templet: formatMoneyToYuan('warrantyAmount')}

        ]
    ];

    // 表格配置
    var tableConfig = {
        defaultParams: {},
        initialSearch: false,
        orderObj: {},
        exportURL: '/report/orderpay/async/export.action',
        config: {
            url: '/report/orderpay/ajax/list.action',
            cols: cols
        }
    };

    /**
     * 渲染日期选择器
     * @param selector 日期选择器的选择器或者 Dom 对象
     */
    function renderDatePicker (selector) {
        var config = {
            elem: selector,
            format: selector.indexOf('Start') !== -1 ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime'
        };

        var minTime = $(selector).data('min') || defaultMinTime;
        if (minTime) {
            config.min = minTime;
        }

        laydate.render(config);
    }

    /**
     * 初始化页面的所有日期组件
     */
    function initALLDatePickers () {
        $.each(datePickerSelectorArray, function (index, keyword) {
            $.each(['Start', 'End'], function (i, suffix) {
                renderDatePicker('#' + keyword + suffix);
            });
        });
    }



    /**
     * 渲染表格
     * @param {object} params 查询参数
     * @returns {object}
     */
    function renderTable (params, data) {
        return zmnTable.init({
            config: {
                ...tableConfig.config,
                toolbar:true,
                defaultToolbar: defaultToolbar,
                elem: '#zmn-pay-table',
                id: 'zmn-pay-table',
                method: 'POST',
                contentType: 'application/json;charset=utf-8',
                limit: 100,
                limits: [100],
                data: data,
                filter: 'zmn-pay-table',
                where: {
                    ...tableConfig.orderObj,
                    ...params
                },
                parseData: function (res) {
                    var count = res.data ?  res.data.count : 0;
                    $('.layui-this').find('.count').text('（共 ' + count + ' 条）');

                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.count > 10000 ? 10000 : res.count, //解析数据长度
                        "data": res.data //解析数据列表
                    };
                },
                done: function (res, curr, count) {
                },
                event: function () {
                }
            }
        });
    }

    // 工具栏
    table.on('toolbar(zmn-pay-table)', function(obj){
        switch(obj.event){
            case 'exports': // 导出
                $('#submit-export').trigger('click');
                break;
        };
    });

    /**
     * 搜索表格
     * @param {object} params 查询参数
     */
    function searchForTable (params, data) {
        tableInstance = renderTable(params, data);
    }

    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams (field) {
        var params = {};

        // 整理时间
        datePickerSelectorArray.forEach(function (keyword) {
            var startSelector = keyword + '.start';
            var endSelector = keyword + '.end';

            if ($('#' + keyword + 'Start').closest('.date-picker-item').hasClass('inline-block'))  {
                var startTime = field[startSelector];
                var endTime = field[endSelector];

                if (startTime || endTime) {
                    /*startTime = startTime ? startTime + ' ' + '00:00:00' : '';
                    endTime = endTime ? endTime + ' ' + '23:59:59' : '';*/

                    params[keyword] = startTime + ',' + endTime;
                }
            }

            field[startSelector] = '';
            field[endSelector] = '';
        });

        // 整理工单号
        if (field['code'] && field['code'].length === 6) {
            params['codeEnd6'] = field['code'];
            field['code'] = '';
        }

        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                params[key] = field[key];
            }
        });

        return params;
    }

    function formatMoneyToYuan(field, showStr) {
        return function (data) {
            var money = data[field];
            if (!money) {
                money = '0.00';
            } else {
                money = NP.round(NP.divide(money, 100), 2);
                money = money.toFixed(2);
            }

            if (showStr) {
                return money + showStr
            } else {
                return money;
            }
        }
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {

        // 监听查询表单提交事件
        form.on('submit(submit-search)', function (obj) {
            var params = normalizeSearchParams(obj.field);
            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            searchForTable(params);
            return false;
        });

        // 监听查询表单导出事件
        form.on('submit(submit-export)', function (obj) {
            var params = normalizeSearchParams(obj.field);

            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            if (!tableConfig.exportURL) {
                layer.msg('请添加导出 URL');
                return false;
            }

            $.ajax({
                type: 'POST',
                url: tableConfig.exportURL,
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(params),
                async:false,
                dataType: 'json',
                success: function (res) {
                    if (res.status == 200) {
                        top.layui.index.openTabsPage(config.elephantHost +'/tapi/export/list.action', "导出文件管理");
                    } else {
                        layer.msg(res.message, {icon: 2});
                    }
                },
                error: function (res) {
                    layer.msg('操作发生异常，请重试', {icon: 5});
                }
            });

            return false;
        });
    }

    /**
     * 初始化页面
     */
    function initPage () {

        if(exportToolbar){
            defaultToolbar.push({
                title: '导出',
                layEvent: 'exports',
                icon: 'layui-icon-export'
            });
        }

        form.render();

        // 初始化页面所有的日期选择器
        initALLDatePickers();
        // 渲染 table
        searchForTable({}, []);

        // 初始化页面数据
        initEvent();
    }

    initPage();
    exports('oms_order_pay_list');
});
